const express = require('express')
const app = express()
app.listen(3000, function () {
    console.log('3000端口开启了，可以访问: http://localhost:3000')
})
app.set('view engine', 'ejs')
const path = require('path')
const formidable = require('formidable')
const fs = require('fs')
const timeStamp = require('time-stamp')
const serveFavicon = require('serve-favicon')
app.use(serveFavicon('favicon.ico'))
app.use(express.urlencoded({
    extended: false
}))
app.use('/static', express.static('static'))
app.use('/uploads', express.static('uploads'))

app.get('/', (req, res) => {
    res.send('我是网站的首页')
})

app.get('/login', (req, res) => {
    filePath = path.join(__dirname, 'views/login.html')
    res.sendFile(filePath)
})

app.get('/register', (req, res) => {
    filePath = path.join(__dirname, 'views/register.html')
    res.sendFile(filePath)
})
app.get('/users', (req, res) => {
    let userData = fs.readFileSync('persons.json','utf8')
    userData = JSON.parse(userData)
    res.render('users',{userData})
})

app.post('/login', (req, res) => {
    let {username = '',password = ''} = req.body
    let result = fs.readFileSync('persons.json', 'utf8')
    result = JSON.parse(result)
    console.log(result);
    let userIndex = result.findIndex(item => item.username == username && item.password == password)
    if (userIndex == -1) {
        res.send('用户名或密码错误')
    } else {
        res.send('登陆成功')
    }
})



app.post('/register', (req, res) => {
    const form = formidable({
        uploadDir: 'uploads'
    })
    form.parse(req, (err, fields, files) => {
        
        let name = files.f1.name
        let suffixName = path.extname(name)
        let t = timeStamp('YYYYMMDDHHmmss')
        let ran = (Math.random() + '').substring(2, 8)
        let oldpath = files.f1.path
        // let newpath = 'uploads/' + t + ran + suffixName
        let avatar = t + ran + suffixName
        let newpath = 'uploads/' + avatar
        fs.renameSync(oldpath, newpath)
        let {
            username = '', password = '', repwd = ''
        } = fields
        // console.log(username, password, repwd);
        // 去除左右空格
        let reg = /^\s+|\s+$/g
        username = username.replace(reg, '')
        if (username == '' || password == '' || repwd == '') {
            res.send('请传递必要参数')
            return
        }
        if (password != repwd) {
            res.send('两次密码不一致')
            return
        }

        let result = fs.readFileSync('persons.json', 'utf8')
        result = JSON.parse(result)
        let userIndex = result.findIndex(item => item.username == username)
        if (userIndex == -1) {
            let time = timeStamp('YYYY-MM-DD HH:mm:ss')
            result.push({
                username,
                password,
                time,
                avatar
            })
            result = JSON.stringify(result)
            fs.writeFileSync('persons.json', result)
            res.send('注册成功')
            return
        } else {
            res.send('用户名已被占用')
            return
        }
    })

    return

})